package controllers;
import business.ApiService;
import business.WxHelper;
import net.sf.json.JSONObject;
import org.apache.axis.utils.StringUtils;
import play.Logger;
import play.cache.Cache;
import play.mvc.Controller;
import utils.DateUtil;

import java.util.Date;
import java.util.UUID;

/**
 * 后台登录
 */
public class WxController extends Controller {
    //static TimedCache<String, String> cache = CacheUtil.newTimedCache(7200);  // 默认缓存24小时
    /**
     * 后台登录页面
     */
    public static void index() {
        String url = "http://carerp.51ls.cc"+ request.url;
        JSONObject jsonObject = getWxConf(url);
        Logger.info(jsonObject.toString());
        render(jsonObject);
    }
    // 我的页面
    public static void mine(){
        render();
    }
    public static void login() {
        render();
    }
    /**
     * 获取微信JS-SDK配置信息
     */
    private static JSONObject getWxConf(String url){
        if(StringUtils.isEmpty(url)){
            url = "http://carerp.51ls.cc";
        }
        JSONObject json = new JSONObject();
        //1.判断缓存中是否有access_token并且没有超过7200(秒)指定时间
        String accessToken = Cache.get("accessToken").toString();
        String jsapi_ticket = Cache.get("jsapi_ticket").toString();
        if(StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(jsapi_ticket)){
            accessToken = WxHelper.getAccessToken();
            Cache.add("accessToken",accessToken);
            jsapi_ticket = WxHelper.getJSApiTicket(accessToken);
            Cache.add("jsapi_ticket",jsapi_ticket);
        }
        //3、时间戳和随机字符串
        //随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        //时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        //4、获取url
        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
        Logger.info(str);
        //6、将字符串进行sha1加密
        String signature = WxHelper.SHA1(str);
        json.put("appId",WxHelper.appid);
        json.put("timestamp",timestamp);
        json.put("nonceStr",noncestr);
        json.put("signature",signature);
        json.put("accessToken",accessToken);
        return json;
    }
    public static void main(String[] args){
        JSONObject jsonObject = getWxConf("http://carerp.51ls.cc");
        Logger.info(jsonObject.toString());
    }
}
